/**
 * 
 */
package string.passed;

/**
 * @author xyyi
 *
 */
public class ReverseWordsInString {

	/**
	 * a stirng like "i like you" to "you like i"
	 */
	public void reverseWords(char[] words) {
		if (words.length == 0)
			return;
		int slow = 0, fast = 0;

		reverse(words, 0, words.length - 1);
		while (fast < words.length && words[fast] == ' ') {
			slow++;
			fast++;
		}
		while (fast < words.length) {
			if (words[fast] == ' ') {
				reverse(words, slow, fast - 1);
				while (fast < words.length && words[fast] == ' ') {
					fast++;
				}
				slow = fast;
			} else {
				fast++;
			}
		}
		if (slow < words.length - 1) {
			reverse(words, slow, fast - 1);
		}
	}

	private void reverse(char[] words, int start, int end) {
		if (!(start >= 0 && end >= start))
			return;
		while (start < end) {
			swap(words, start++, end--);
		}
	}

	private void swap(char[] words, int i, int j) {
		if (i < 0 || j < 0)
			return;
		char tmp = words[i];
		words[i] = words[j];
		words[j] = tmp;
	}

	/**
	 * 
	 */
	public ReverseWordsInString() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ReverseWordsInString rws = new ReverseWordsInString();
		String str = " I  like you    ";
		char[] words = str.toCharArray();

		rws.reverseWords(words);
		System.out.printf("%s : %s", str, new String(words));
	}

}
